<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

<!-- 数组扁平化 -->
<!-- 数组转成树型结构  -->
<script>
    const list = [{
        id: 1,
        name: '张三',
        pid: 0
    }, {
        id: 2,
        name: '李四',
        pid: 1
    }, {
        id: 3,
        name: '赵五',
        pid: 1
    }, {
        id: 4,
        name: '王六',
        pid: 2
    }, {
        id: 5,
        name: '老大',
        pid: 2
    }, {
        id: 6,
        name: '陈五',
        pid: 3
    }, {
        id: 7,
        name: '张九',
        pid: 3
    }, {
        id: 8,
        name: '张拴',
        pid: 3
    }, {
        id: 9,
        name: '赵一',
        pid: 4
    }]
    const map = []
    list.forEach(item => {
        map[item.id] = item
        item.children = []
    })
    const treeList = []

    list.forEach(item => {
        if (item.pid) { // 有父节点
            const parent = map[item.pid]
            parent.children.push(item)
        } else { // 根节点
            treeList.push(item)
        }
    })

    console.log(treeList)

    var arr1 = [1, 2, 3, [1, 2, 3, 4, [2, 3, 4]]];

    function flatten(arr) {
        var res = [];
        for (let i = 0, length = arr.length; i < length; i++) {
            if (Array.isArray(arr[i])) {
                res = res.concat(flatten(arr[i])); //concat 并不会改变原数组
                //res.push(...flatten(arr[i])); //扩展运算符
            } else {
                res.push(arr[i]);
            }
        }
        return res;
    }

    console.log(flatten(arr1)); //[1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
</script>
</body>

</html>
